package comprehensive_practice;

import Utils.FileUtil;
import data_manipulate.TopN;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/*
 task word count
 data source in hbase
 write to hdfs
 write back to hbase
ROW COLUMN
1  column=cf:hui, timestamp=2024-03-15T11:09:48.904, value=hello world
 table name hello in hbase
 */
public class HBaseWordCount {
    // could be set in input param, here we wield into program
    private static String tableName = "hello";
    private static String outputPath = "hdfs://localhost:9000/comprehensive/hbasewc_output";

    public static void main(String[] args)
            throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        // prepare hbase connection
        Connection conn = ConnectionFactory.createConnection(conf);
        Admin admin = conn.getAdmin();
        TableName tName = TableName.valueOf(tableName);
        if (admin.tableExists(tName)) {
            FileUtil fileUtil = new FileUtil(conf, outputPath);
            fileUtil.doDelete(outputPath);

            Scan scan = new Scan();

            Job job = Job.getInstance(conf, "HBase WordCount");
            job.setJarByClass(HBaseWordCount.class);
            // for top problem, we only need on reducer process.
            job.setNumReduceTasks(1);

            TableMapReduceUtil.initTableMapperJob(tName, scan,doMapper.class,
                    Text.class, IntWritable.class, job);

            job.setCombinerClass(doReducer.class);

            job.setReducerClass(doReducer.class);
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(IntWritable.class);

            FileOutputFormat.setOutputPath(job, new Path(outputPath));
            System.exit(job.waitForCompletion(true) ? 0 : 1);
        } else {
            System.out.println("table doesn't exist! Now exiting ...");
            System.exit(1);
        }
    }

    public static class doMapper extends TableMapper<Text, IntWritable> {

        private IntWritable one = new IntWritable(1);

        @Override
        protected void map(ImmutableBytesWritable key, Result value, Mapper<ImmutableBytesWritable, Result, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            Cell[] cells = value.rawCells();
            // only one line included
            String lines = Bytes.toString(CellUtil.cloneValue(cells[0]));
            String[] splits = lines.trim().split(" ");
            for (String split : splits) {
                context.write(new Text(split), one);
            }

        }
    }

    public static class doReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

        private int sum;

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            sum = 0;
            for (IntWritable value: values) {
                sum += value.get();
            }
            context.write(key, new IntWritable(sum));
        }
    }

}
